package com.yangkz.code.config;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @ProjectName: mybatis-gencode
 * @Package: com.yangkz.code.config
 * @ClassName: DataSourceConfig
 * @Author: yangkunzhen
 * @Description: TODO
 * @Date: 2019/7/5 0005 上午 2:30
 * @Version: 1.0
 */
@Configuration
public class DataSourceConfig {

    @Value("${com.yangkz.code.modelPackage}")
    private String modelPackage;

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setTypeAliasesPackage(modelPackage);

        //配置分页插件，详情请查阅官方文档
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        //分页尺寸为0时查询所有纪录不再执行分页
        properties.setProperty( "pageSizeZero", "true");
        //页码<=0 查询第一页，页码>=总页数查询最后一页
        properties.setProperty( "reasonable", "true");
        //支持通过 Mapper 接口参数来传递分页参数
        properties.setProperty( "supportMethodsArguments", "true" );
        pageHelper.setProperties( properties );

        //添加插件
        factory.setPlugins( new Interceptor[]{pageHelper} );

        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factory.setMapperLocations( resolver.getResources( "classpath:mapper/*.xml" ) );
        return factory.getObject();
    }
}
